package org.seven.jrdp.commons.shiro.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.seven.jrdp.commons.constant.GlobalContants;
import org.seven.jrdp.commons.model.MenuNode;
import org.seven.jrdp.commons.util.JsonUtils;

public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	private String id;
	private String account;
	private String password;
	private String name;

	private Organ organ;
	private List<Role> roles;
	private List<Resource> resources;

	private Set<String> permissions;
	private String menu;
	private String roleName;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Organ getOrgan() {
		return organ;
	}

	public void setOrgan(Organ organ) {
		this.organ = organ;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public List<Resource> getResources() {
		return resources;
	}

	public void setResources(List<Resource> resources) {
		this.resources = resources;
	}

	public Set<String> getPermissions() {
		if (permissions == null) {
			permissions = new HashSet<String>();
			for (Resource resource : getResources()) {
				if (resource.getUrl() != null && !"".equals(resource.getUrl())) {
					if (resource.isDisplay()) {
						permissions.add(resource.getCode());
					}
				}
			}
		}
		return permissions;
	}

	public String getMenu() {
		if (menu == null) {
			List<MenuNode> menus = new ArrayList<MenuNode>();
			for (Resource resource : getResources()) {
				if (resource.isMenu() && resource.isDisplay()) {
					MenuNode menu = new MenuNode();
					menu.setId(resource.getId());
					menu.setText(resource.getName());
					menu.setIconCls(resource.getIcon());
					menu.setUrl(resource.getUrl());
					menu.setPid(resource.getPid());
					menus.add(menu);
				}
			}
			menu = JsonUtils.getJson(menus);
		}
		return menu;
	}

	public boolean isAdmin() {
		return GlobalContants.ADMIN.equals(getId());
	}

	public String getRoleName() {
		if (roleName == null) {
			List<String> list = new ArrayList<String>();
			for (Role role : getRoles()) {
				list.add(role.getName());
			}
			roleName = StringUtils.join(list.iterator(), ",");
		}
		return roleName;
	}

	@Override
	public String toString() {
		return String.format("%s(%s)", account, name);
	}
}